
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
# @file   : aqi.py
# @author : weichy
# @date   : 2019/01/08
# @version: 3.0
# @desc   :  1.0AQI计算
            2.0 读取json中api前5的数据
            3.0 csv文件互换

'''
import json
import csv

def call_linear(iaqi_lo,iaqi_hi,bp_lo,bp_hi,cp):
    # 线性转换 范围缩放
    iaqi = (iaqi_hi-iaqi_lo) * (cp-bp_lo) /(bp_hi-bp_lo) + iaqi_lo
    return iaqi


def cal_pm_iaqi(pm_val):
    # 计算pm2.5 IAQI
    if 0 <=pm_val<=35:
        iaqi = call_linear(0,50,0,35,pm_val)
    elif 36<=pm_val <=75:
        iaqi = call_linear(50,100,35,75,pm_val)
    elif 76<=pm_val<=115:
        iaqi = call_linear(100,150,75,115,pm_val)
    else:
        pass

    return iaqi

def cal_co_iaqi(co_val):
    # 计算pm2.5 IAQI
    if 0 <=co_val<=2:
        iaqi = call_linear(0,50,0,3,co_val)
    elif 3<=co_val <=4:
        iaqi = call_linear(50,100,3,4,co_val)
    else:
        pass
    return iaqi
    

def cal_aqi(param_list):
    '''
    API计算
    '''
    pm_val = param_list[0]
    co_val = param_list[1]

    pm_iaqi = cal_pm_iaqi(pm_val)
    co_iaqi = cal_co_iaqi(co_val)

    iaqi_list = []
    iaqi_list.append(pm_iaqi)
    iaqi_list.append(co_iaqi)

    aqi = max(iaqi_list)

    return aqi

def process_json_file(filepath):
    '''
    解码json文件
    '''
    with open(filepath,mode='r',encoding='utf-8') as f:
        city_list = json.load(f)

        return  city_list

def main():

    filepath = input('请输入json文件名称：')
    city_list = process_json_file(filepath)
    city_list.sort(key=lambda city:city['aqi'])
    top5_list = city_list[:5]

    with open('top5_aqi.json',mode='w',encoding='utf-8') as f:
        json.dump(top5_list,f,ensure_ascii=False)

    lines = []
    lines.append(list(city_list[0].keys()))
    for city in city_list:
        lines.append(list(city.values()))
    print(lines)
    with open('aqi.csv','w',encoding='utf-8',newline='') as f:
        write = csv.writer(f)
        for line in lines:
            write.writerow(line)


    # print('请输入一下信息，用空格分割')
    # input_str = input('(1)PM2.5  (2)Co:')
    # str_list = input_str.split(' ')
    # pm_val = float(str_list[0])
    # co_val = float(str_list[1])
    # param_list = []
    # param_list.append(pm_val)
    # param_list.append(co_val)

    # # 调用AQI计算函数
    # aqi_val = cal_aqi(param_list)

    # print('空气质量指数为{}。'.format(aqi_val))

if  __name__ == '__main__':
    main()